import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart' show ImagePicker, XFile, ImageSource;
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'db_helper.dart';
import 'statistics_page.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:path/path.dart' as path_helper;
import 'package:window_manager/window_manager.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:audioplayers/audioplayers.dart';

void main() async {
  // 确保 Flutter 绑定初始化
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化数据库路径
  if (Platform.isWindows) {
    // 确保 sqflite 在 Windows 上正常工作
    sqfliteFfiInit();
    // 设置数据库路径
    final appDocDir = await getApplicationDocumentsDirectory();
    final dbPath = path_helper.join(appDocDir.path, 'databases');
    await Directory(dbPath).create(recursive: true);
    // 设置 databaseFactory
    databaseFactory = databaseFactoryFfi;
    
    // 初始化窗口管理器并设置中文标题
    await windowManager.ensureInitialized();
    await windowManager.waitUntilReadyToShow();
    await windowManager.setTitle('报销小帮手');
  }

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '我的记账本',
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('zh', 'CN'),
        Locale('en', 'US'),
      ],
      locale: const Locale('zh'),
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.blue,
          secondary: Colors.blueAccent,
        ),
        useMaterial3: true,
        cardTheme: CardTheme(
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        floatingActionButtonTheme: const FloatingActionButtonThemeData(
          elevation: 4,
        ),
      ),
      home: const MyHomePage(title: '我的记账本'),
    );
  }
}

// 添加类别枚举
enum ExpenseCategory {
  dining('餐饮费'),
  material('材料费'),
  equipment('设备费'),
  meeting('会议费'),
  other('其他');

  final String label;
  const ExpenseCategory(this.label);
}

// 更新 Transaction 类
class Transaction {
  final int? id;
  final String title;
  final double amount;
  final DateTime date;
  final bool isExpense;
  final ExpenseCategory category;
  final String note;
  final String? imagePath;
  bool isReimbursed;

  Transaction({
    this.id,
    required this.title,
    required this.amount,
    required this.date,
    required this.isExpense,
    required this.category,
    required this.note,
    this.imagePath,
    this.isReimbursed = false,
  });

  Map<String, dynamic> toJson() => {
    'id': id,
    'title': title,
    'amount': amount,
    'date': date.toIso8601String(),
    'isExpense': isExpense,
    'category': category.name,
    'note': note,
    'imagePath': imagePath,
    'isReimbursed': isReimbursed,
  };

  factory Transaction.fromJson(Map<String, dynamic> json) => Transaction(
    id: json['id'],
    title: json['title'],
    amount: json['amount'],
    date: DateTime.parse(json['date']),
    isExpense: json['isExpense'],
    category: ExpenseCategory.values.firstWhere(
      (e) => e.name == json['category'],
      orElse: () => ExpenseCategory.other,
    ),
    note: json['note'],
    imagePath: json['imagePath'],
    isReimbursed: json['isReimbursed'],
  );
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<Transaction> _transactions = [];
  final _titleController = TextEditingController();
  final _amountController = TextEditingController();
  final _noteController = TextEditingController();
  bool _isExpense = true;
  ExpenseCategory _selectedCategory = ExpenseCategory.dining;
  String? _selectedImagePath;
  final ImagePicker _picker = ImagePicker();
  final AudioPlayer _audioPlayer = AudioPlayer();

  @override
  void initState() {
    super.initState();
    _loadTransactions();
    // 预加载音频文件
    _audioPlayer.setSource(AssetSource('audio/ding.mp3'));
    _audioPlayer.setVolume(0.5); // 设置音量
  }

  Future<void> _loadTransactions() async {
    try {
      final transactions = await DBHelper.getTransactions();
      setState(() {
        _transactions.clear();
        _transactions.addAll(
          transactions.map((item) => Transaction.fromJson(item)).toList(),
        );
      });
    } catch (e) {
      print('Error loading transactions: $e');
    }
  }

  void _addTransaction() {
    final title = _titleController.text;
    final amount = double.tryParse(_amountController.text) ?? 0.0;
    final note = _noteController.text;

    if (title.isEmpty || amount <= 0) {
      return;
    }

    // 验证图片是否存在
    if (_selectedImagePath != null) {
      final imageFile = File(_selectedImagePath!);
      if (!imageFile.existsSync()) {
        showDialog<void>(
          context: context,
          builder: (BuildContext dialogContext) => AlertDialog(
            title: const Text('错误'),
            content: const Text('选择的图片不存在或无法访问'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(dialogContext).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
        return;
      }
    }

    final transaction = Transaction(
      title: title,
      amount: amount,
      date: DateTime.now(),
      isExpense: _isExpense,
      category: _selectedCategory,
      note: note,
      imagePath: _selectedImagePath,
    );

    try {
      DBHelper.insertTransaction(transaction.toJson()).then((id) {
        setState(() {
          _transactions.add(Transaction(
            id: id,
            title: transaction.title,
            amount: transaction.amount,
            date: transaction.date,
            isExpense: transaction.isExpense,
            category: transaction.category,
            note: transaction.note,
            imagePath: transaction.imagePath,
          ));
        });

        _titleController.clear();
        _amountController.clear();
        _noteController.clear();
        _selectedImagePath = null;
        Navigator.pop(context);
      });
    } catch (e) {
      print('Error saving transaction: $e');
      if (mounted) {
        showDialog<void>(
          context: context,
          builder: (BuildContext dialogContext) => AlertDialog(
            title: const Text('错误'),
            content: Text('保存记录失败: $e'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(dialogContext).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  bool get isWindows => Platform.isWindows;

  Future<void> _pickImage(StateSetter setDialogState) async {
    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 800,
        maxHeight: 800,
        imageQuality: 80,
      );

      if (image != null) {
        // 为 Windows 平台特别处理图片存储
        if (isWindows) {
          final Directory appDir = await getApplicationDocumentsDirectory();
          final String imagesDir = '${appDir.path}\\images';
          await Directory(imagesDir).create(recursive: true);
          
          final String fileName = '${DateTime.now().millisecondsSinceEpoch}_${path_helper.basename(image.path)}';
          final String savedPath = '$imagesDir\\$fileName';
          
          await File(image.path).copy(savedPath);
          
          setDialogState(() {
            _selectedImagePath = savedPath;
          });
        } else {
          setDialogState(() {
            _selectedImagePath = image.path;
          });
        }
        print('Selected image path: ${_selectedImagePath}');
      }
    } catch (e) {
      print('Error picking image: $e');
      if (mounted) {
        showDialog<void>(
          context: context,
          builder: (BuildContext dialogContext) => AlertDialog(
            title: const Text('错误'),
            content: Text('选择图片失败: $e'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(dialogContext).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  void _showAddTransactionDialog() {
    // 重置表单状态
    _titleController.clear();
    _amountController.clear();
    _noteController.clear();
    _selectedImagePath = null;
    _isExpense = true;
    _selectedCategory = ExpenseCategory.dining;

    showDialog<void>(
      context: context,
      barrierDismissible: false, // 防止点击外部关闭对话框
      builder: (BuildContext dialogContext) => StatefulBuilder(
        builder: (BuildContext context, StateSetter setDialogState) => Dialog(
          child: Container(
            constraints: const BoxConstraints(maxWidth: 400),
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  const Text(
                    '添加新记录',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _titleController,
                    decoration: InputDecoration(
                      labelText: '标题',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      filled: true,
                      fillColor: Colors.grey[50],
                    ),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _amountController,
                    decoration: InputDecoration(
                      labelText: '金额',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      filled: true,
                      fillColor: Colors.grey[50],
                      prefixText: '￥',
                    ),
                    keyboardType: const TextInputType.numberWithOptions(decimal: true),
                  ),
                  const SizedBox(height: 16),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.grey.shade400),
                      color: Colors.grey[50],
                    ),
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton<ExpenseCategory>(
                        isExpanded: true,
                        value: _selectedCategory,
                        items: ExpenseCategory.values.map((category) {
                          return DropdownMenuItem(
                            value: category,
                            child: Text(category.label),
                          );
                        }).toList(),
                        onChanged: (value) {
                          setDialogState(() {
                            _selectedCategory = value!;
                          });
                        },
                      ),
                    ),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _noteController,
                    decoration: InputDecoration(
                      labelText: '备注',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      filled: true,
                      fillColor: Colors.grey[50],
                    ),
                    maxLines: 3,
                  ),
                  const SizedBox(height: 16),
                  Container(
                    width: double.infinity,
                    height: _selectedImagePath != null ? 200 : 80,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey.shade300),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: _selectedImagePath != null
                        ? Stack(
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: Image.file(
                                  File(_selectedImagePath!),
                                  width: double.infinity,
                                  height: double.infinity,
                                  fit: BoxFit.cover,
                                ),
                              ),
                              Positioned(
                                right: 8,
                                top: 8,
                                child: IconButton(
                                  icon: const Icon(Icons.close),
                                  color: Colors.white,
                                  onPressed: () {
                                    setDialogState(() {
                                      _selectedImagePath = null;
                                    });
                                  },
                                ),
                              ),
                            ],
                          )
                        : InkWell(
                            onTap: () => _pickImage(setDialogState),
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.grey[50],
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(
                                    Icons.add_photo_alternate,
                                    size: 32,
                                    color: Theme.of(context).primaryColor,
                                  ),
                                  const SizedBox(height: 8),
                                  Text(
                                    '添加票据照片',
                                    style: TextStyle(
                                      color: Theme.of(context).primaryColor,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                  ),
                  const SizedBox(height: 24),
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () {
                            setDialogState(() => _isExpense = true);
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: _isExpense ? Colors.red.shade100 : Colors.grey.shade100,
                            foregroundColor: _isExpense ? Colors.red : Colors.grey,
                            padding: const EdgeInsets.symmetric(vertical: 12),
                          ),
                          child: const Text('支出', style: TextStyle(fontSize: 16)),
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () {
                            setDialogState(() => _isExpense = false);
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: !_isExpense ? Colors.green.shade100 : Colors.grey.shade100,
                            foregroundColor: !_isExpense ? Colors.green : Colors.grey,
                            padding: const EdgeInsets.symmetric(vertical: 12),
                          ),
                          child: const Text('收入', style: TextStyle(fontSize: 16)),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      TextButton(
                        onPressed: () => Navigator.pop(context),
                        child: Text('取消', style: TextStyle(color: Colors.grey[600])),
                      ),
                      const SizedBox(width: 8),
                      ElevatedButton(
                        onPressed: _addTransaction,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Theme.of(context).colorScheme.primary,
                          foregroundColor: Colors.white,
                        ),
                        child: const Text('添加'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _toggleReimbursementStatus(int index) async {
    final tx = _transactions[index];
    tx.isReimbursed = !tx.isReimbursed;
    
    try {
      await DBHelper.updateTransaction(tx.toJson());
      setState(() {});
      
      // 播放提示音
      if (tx.isReimbursed) {
        await _audioPlayer.play(AssetSource('audio/ding.mp3'));
      }
    } catch (e) {
      print('Error updating reimbursement status: $e');
      if (mounted) {
        showDialog<void>(
          context: context,
          builder: (BuildContext dialogContext) => AlertDialog(
            title: const Text('错误'),
            content: Text('更新报销状态失败: $e'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(dialogContext).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  void _editTransaction(Transaction tx) {
    _titleController.text = tx.title;
    _amountController.text = tx.amount.toString();
    _noteController.text = tx.note;
    _isExpense = tx.isExpense;
    _selectedCategory = tx.category;
    _selectedImagePath = tx.imagePath;

    showDialog<void>(
      context: context,
      builder: (BuildContext dialogContext) => StatefulBuilder(
        builder: (BuildContext context, StateSetter setDialogState) => Dialog(
          child: Container(
            constraints: const BoxConstraints(maxWidth: 400),
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  const Text(
                    '编辑记录',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _titleController,
                    decoration: InputDecoration(
                      labelText: '标题',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      filled: true,
                      fillColor: Colors.grey[50],
                    ),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _amountController,
                    decoration: InputDecoration(
                      labelText: '金额',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      filled: true,
                      fillColor: Colors.grey[50],
                      prefixText: '￥',
                    ),
                    keyboardType: const TextInputType.numberWithOptions(decimal: true),
                  ),
                  const SizedBox(height: 16),
                  TextField(
                    controller: _noteController,
                    decoration: InputDecoration(
                      labelText: '备注',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      filled: true,
                      fillColor: Colors.grey[50],
                    ),
                    maxLines: 3,
                  ),
                  const SizedBox(height: 16),
                  DropdownButtonFormField<ExpenseCategory>(
                    value: _selectedCategory,
                    decoration: InputDecoration(
                      labelText: '类别',
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      filled: true,
                      fillColor: Colors.grey[50],
                    ),
                    items: ExpenseCategory.values.map((category) {
                      return DropdownMenuItem(
                        value: category,
                        child: Text(category.label),
                      );
                    }).toList(),
                    onChanged: (ExpenseCategory? value) {
                      if (value != null) {
                        setDialogState(() {
                          _selectedCategory = value;
                        });
                      }
                    },
                  ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () {
                            setDialogState(() => _isExpense = true);
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: _isExpense ? Colors.red.shade100 : Colors.grey.shade100,
                            foregroundColor: _isExpense ? Colors.red : Colors.grey,
                            padding: const EdgeInsets.symmetric(vertical: 12),
                          ),
                          child: const Text('支出', style: TextStyle(fontSize: 16)),
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () {
                            setDialogState(() => _isExpense = false);
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: !_isExpense ? Colors.green.shade100 : Colors.grey.shade100,
                            foregroundColor: !_isExpense ? Colors.green : Colors.grey,
                            padding: const EdgeInsets.symmetric(vertical: 12),
                          ),
                          child: const Text('收入', style: TextStyle(fontSize: 16)),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 24),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      TextButton(
                        onPressed: () => Navigator.pop(context),
                        child: Text('取消', style: TextStyle(color: Colors.grey[600])),
                      ),
                      const SizedBox(width: 8),
                      ElevatedButton(
                        onPressed: () => _updateTransaction(tx.id!),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Theme.of(context).colorScheme.primary,
                          foregroundColor: Colors.white,
                        ),
                        child: const Text('保存'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _updateTransaction(int id) async {
    final title = _titleController.text;
    final amount = double.tryParse(_amountController.text) ?? 0.0;
    final note = _noteController.text;

    if (title.isEmpty || amount <= 0) {
      return;
    }

    final transaction = Transaction(
      id: id,
      title: title,
      amount: amount,
      date: DateTime.now(),
      isExpense: _isExpense,
      category: _selectedCategory,
      note: note,
      imagePath: _selectedImagePath,
    );

    try {
      await DBHelper.updateTransaction(transaction.toJson());
      await _loadTransactions();  // 重新加载数据
      if (mounted) {
        Navigator.pop(context);
        _titleController.clear();
        _amountController.clear();
        _noteController.clear();
        _selectedImagePath = null;
      }
    } catch (e) {
      print('Error updating transaction: $e');
      if (mounted) {
        showDialog<void>(
          context: context,
          builder: (BuildContext dialogContext) => AlertDialog(
            title: const Text('错误'),
            content: Text('更新记录失败: $e'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(dialogContext).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  Future<void> _deleteTransaction(int id) async {
    try {
      await DBHelper.deleteTransaction(id);
      await _loadTransactions();  // 重新加载数据
    } catch (e) {
      print('Error deleting transaction: $e');
      if (mounted) {
        showDialog<void>(
          context: context,
          builder: (BuildContext dialogContext) => AlertDialog(
            title: const Text('错误'),
            content: Text('删除记录失败: $e'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(dialogContext).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    double unreimbursedTotal = _transactions.where((tx) => !tx.isReimbursed).fold(
      0.0,
      (sum, tx) => tx.isExpense ? sum - tx.amount : sum + tx.amount,
    );
    
    double reimbursedTotal = _transactions.where((tx) => tx.isReimbursed).fold(
      0.0,
      (sum, tx) => tx.isExpense ? sum - tx.amount : sum + tx.amount,
    );

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
        elevation: 2,
        title: Text(widget.title),
        actions: [
          IconButton(
            icon: const Icon(Icons.analytics),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const StatisticsPage()),
              );
            },
          ),
        ],
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(70),
          child: Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Text(
                  '当前余额: ￥${unreimbursedTotal.toStringAsFixed(2)}',
                  style: const TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 4),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.monetization_on,  // 使用金币图标
                      size: 16,
                      color: Colors.amber[300],  // 金色
                    ),
                    const SizedBox(width: 4),
                    Text(
                      '已报销: ',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.amber[100],
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    Text(
                      '￥${reimbursedTotal.abs().toStringAsFixed(2)}',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.amber[300],
                        fontWeight: FontWeight.bold,
                        shadows: [
                          Shadow(
                            color: Colors.black.withOpacity(0.3),
                            offset: const Offset(0, 1),
                            blurRadius: 2,
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 4),
                    Icon(
                      Icons.monetization_on,  // 对称放置另一个金币图标
                      size: 16,
                      color: Colors.amber[300],  // 金色
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
      body: _transactions.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.account_balance_wallet_outlined,
                    size: 64,
                    color: Colors.grey[400],
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '还没有任何记录',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '点击右下角的按钮添加新记录',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
            )
          : ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: _transactions.length,
              itemBuilder: (ctx, index) {
                final tx = _transactions[index];
                return _buildTransactionItem(tx, index);
              },
            ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _showAddTransactionDialog,
        icon: const Icon(Icons.add),
        label: const Text('添加记录'),
      ),
    );
  }

  Widget _buildTransactionItem(Transaction tx, int index) {
    return InkWell(
      onLongPress: () {
        showDialog<void>(
          context: context,
          builder: (BuildContext dialogContext) => AlertDialog(
            title: const Text('操作选项'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ListTile(
                  leading: const Icon(Icons.edit),
                  title: const Text('编辑'),
                  onTap: () {
                    Navigator.pop(dialogContext);
                    _editTransaction(tx);
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.delete, color: Colors.red),
                  title: const Text('删除', style: TextStyle(color: Colors.red)),
                  onTap: () {
                    Navigator.pop(dialogContext);
                    showDialog<void>(
                      context: context,
                      builder: (BuildContext confirmContext) => AlertDialog(
                        title: const Text('确认删除'),
                        content: const Text('确定要删除这条记录吗？此操作不可撤销。'),
                        actions: [
                          TextButton(
                            onPressed: () => Navigator.pop(confirmContext),
                            child: const Text('取消'),
                          ),
                          TextButton(
                            onPressed: () {
                              Navigator.pop(confirmContext);
                              _deleteTransaction(tx.id!);
                            },
                            child: const Text('删除', style: TextStyle(color: Colors.red)),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
        );
      },
      child: Card(
        margin: const EdgeInsets.only(bottom: 12),
        child: Column(
          children: [
            ListTile(
              contentPadding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
              leading: CircleAvatar(
                radius: 24,
                backgroundColor: tx.isReimbursed
                    ? Colors.grey.shade200
                    : (tx.isExpense ? Colors.red.shade50 : Colors.green.shade50),
                child: Icon(
                  tx.isExpense ? Icons.remove : Icons.add,
                  color: tx.isReimbursed
                      ? Colors.grey
                      : (tx.isExpense ? Colors.red : Colors.green),
                  size: 28,
                ),
              ),
              title: Text(
                tx.title,
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  decoration: tx.isReimbursed ? TextDecoration.lineThrough : null,
                  color: tx.isReimbursed ? Colors.grey : Colors.black87,
                ),
              ),
              subtitle: Text(
                '${tx.date.year}-${tx.date.month.toString().padLeft(2, '0')}-${tx.date.day.toString().padLeft(2, '0')}\n${tx.isReimbursed ? "已报销" : "未报销"}',
                style: TextStyle(color: Colors.grey[600]),
              ),
              trailing: SizedBox(
                width: 120,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text(
                          '${tx.isExpense ? "-" : "+"}￥${tx.amount.toStringAsFixed(2)}',
                          style: TextStyle(
                            fontSize: 16,
                            color: tx.isReimbursed
                                ? Colors.grey
                                : (tx.isExpense ? Colors.red : Colors.green),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: tx.isReimbursed
                                ? Colors.grey.shade100
                                : (tx.isExpense 
                                    ? Colors.red.shade50.withOpacity(0.7)
                                    : Colors.green.shade50.withOpacity(0.7)),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                              color: tx.isReimbursed
                                  ? Colors.grey.shade300
                                  : (tx.isExpense 
                                      ? Colors.red.shade200
                                      : Colors.green.shade200),
                              width: 1.5,
                            ),
                          ),
                          child: Text(
                            tx.category.label,
                            style: TextStyle(
                              fontSize: 11,
                              fontWeight: FontWeight.w600,
                              color: tx.isReimbursed
                                  ? Colors.grey
                                  : (tx.isExpense 
                                      ? Colors.red.shade700
                                      : Colors.green.shade700),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      width: 32,
                      child: IconButton(
                        icon: Icon(
                          tx.isReimbursed ? Icons.check_circle : Icons.check_circle_outline,
                          color: tx.isReimbursed ? Colors.grey : Colors.blue,
                          size: 20,
                        ),
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(
                          minWidth: 32,
                          minHeight: 32,
                        ),
                        onPressed: () => _toggleReimbursementStatus(index),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            if (tx.note.isNotEmpty)
              Padding(
                padding: const EdgeInsets.fromLTRB(64, 0, 16, 8),
                child: Row(
                  children: [
                    Icon(Icons.note, size: 14, color: Colors.grey[400]),
                    const SizedBox(width: 4),
                    Expanded(
                      child: Text(
                        tx.note,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            if (tx.imagePath != null)
              Padding(
                padding: const EdgeInsets.fromLTRB(64, 0, 16, 8),
                child: GestureDetector(
                  onTap: () {
                    showDialog(
                      context: context,
                      builder: (ctx) => Dialog(
                        child: Stack(
                          children: [
                            Image.file(
                              File(tx.imagePath!),
                              fit: BoxFit.contain,
                            ),
                            Positioned(
                              right: 8,
                              top: 8,
                              child: Material(
                                color: Colors.transparent,
                                child: IconButton(
                                  icon: const Icon(Icons.close),
                                  color: Colors.white,
                                  onPressed: () => Navigator.of(context).pop(),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  child: Container(
                    height: 120,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.grey.shade200),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: Image.file(
                        File(tx.imagePath!),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _audioPlayer.dispose(); // 释放音频播放器资源
    _titleController.dispose();
    _amountController.dispose();
    _noteController.dispose();
    super.dispose();
  }
}
